/**
 * MIT License
 * 项目核心Js类，负责项目前端模板方面的初始化等操作
 *
 */
(function ($) {
    $.extend($.fn, {
        zydSelect: function (options) {
            var op = $.extend({firstText: '请选择', firstValue: ''}, options);

            function onchange(event) {
                var $child = $("#" + event.data.$child);
                var $parent = event.data.$parent;
                var parentValue = $parent.val();
                if (!$child || $child.size() == 0 || !parentValue) {
                    $parent.attr('name', $child.attr('name'));
                    $child.attr('disabled', 'disabled');
                    $child.html('');
                    return false;
                }
                $.ajax({
                    type: 'POST',
                    dataType: "json",
                    url: event.data.childUrl.replace("{value}", encodeURIComponent($parent.val())),
                    cache: false,
                    data: {},
                    success: function (json) {
                        var childData;
                        if (json.status != 200 || !(childData = json.data) || childData.length == 0) {
                            console.error(json.message);
                            return false;
                        }
                        $child.removeAttr('disabled');
                        $parent.removeAttr('name');
                        var html = '<option value="' + op.firstValue + '">' + op.firstText + '</option>';
                        $.each(childData, function (i) {
                            html += '<option value="' + childData[i]['value'] + '">' + childData[i]['text'] + '</option>';
                        });
                        $child.html(html);
                    },
                    error: $.tool.ajaxError
                });
            }

            return this.each(function (i) {
                var $this = $(this);
                var child = $this.data("child");
                var childUrl = $this.data('child-url') || '';
                var defaultText = $this.data('default-text') || '';
                if (child && childUrl) {
                    $this.unbind("change", onchange).bind("change", {
                        $child: child,
                        childUrl: childUrl,
                        $parent: $this,
                        defaultText: defaultText
                    }, onchange);
                }
            });
        }
    });
})(jQuery);
var ssr = window.ssr || {
    initSidebar: function () {
        function a() {
            $(".right_col").css("min-height", $(window).height());
            // body 高度
            var body = $("body").outerHeight();
            // hasClass   body是否包含 "footer_fixed" 类  页脚高度
            var b = $("body").hasClass("footer_fixed") ? -10 : $("footer").height();
            var c = $(".left_col").eq(1).height()
            // 右边显示div高度
            var rightCol = $(".right_col").outerHeight();
            $("#contentId").height(rightCol - b );
            // 菜单栏div高度
            $("#sidebar-menu").height(rightCol-$(".clearfix").height() - $(".profile").height()-20);
            $("#sidebar-menu").css("position: relative; overflow: hidden; width: auto; OVERFLOW-Y: auto;");
        };


        $("#sidebar-menu").find("a").on("click", function (b) {
            var c = $(this).parent();
            c.is(".active") ? (c.removeClass("active active-sm"), $("ul:first", c).slideUp(function () {
                a()
            })) : (c.parent().is(".child_menu") ? $("body").is(".nav-sm") && ($("#sidebar-menu").find("li").removeClass("active active-sm"), $("#sidebar-menu").find("li ul").slideUp()) : ($("#sidebar-menu").find("li").removeClass("active active-sm"), $("#sidebar-menu").find("li ul").slideUp()), c.addClass("active"), $("ul:first", c).slideDown(function () {
                a()
            }))
        })


        $("#menu_toggle").on("click", function () {
            $("body").hasClass("nav-md") ? ($("#sidebar-menu").find("li.active ul").hide(), $("#sidebar-menu").find("li.active").addClass("active-sm").removeClass("active")) : ($("#sidebar-menu").find("li.active-sm ul").show(), $("#sidebar-menu").find("li.active-sm").addClass("active").removeClass("active-sm")), $("body").toggleClass("nav-md nav-sm"), a()
        })


        $("#sidebar-menu").find('a[href="' + CURRENT_URL + '"]').parent("li").addClass("current-page"), $("#sidebar-menu").find("a").filter(function () {
            return this.href == CURRENT_URL
        })
        //     .parent("li").addClass("current-page").parents("ul").slideDown(function () {
        //     a()
        // })
            .parent().addClass("active")

        $(window).smartresize(function () {
            a()
        })
        a()
        $.fn.mCustomScrollbar && $(".menu_fixed").mCustomScrollbar({
            autoHideScrollbar: !0,
            theme: "minimal",
            mouseWheel: {
                preventDefault: !0
            }
        })
    },
    initDaterangepicker: function () {
        $('.myDatepicker').datetimepicker({
            format: 'YYYY-MM-DD HH:mm:ss',
            ignoreReadonly: true,
            allowInputToggle: true
        });
    },
    initValidator: function () {
        "undefined" != typeof validator && (console.log("ssr.initValidator"), validator.message.date = "not a real date", $("form").on("blur", "input[required], input.optional, select.required", validator.checkField).on("change", "select.required", validator.checkField).on("keypress", "input[required][pattern]", validator.keypress), $(".multi.required").on("keyup blur", "input", function () {
            validator.checkField.apply($(this).siblings().last()[0])
        }), $("form").submit(function (a) {
            a.preventDefault();
            var b = !0;
            return validator.checkAll($(this)) || (b = !1), b && this.submit(), !1
        }));
    }
};

function countChecked() {
    "all" === checkState && $(".bulk_action input[name='table_records']").iCheck("check"),
    "none" === checkState && $(".bulk_action input[name='table_records']").iCheck("uncheck");
    var a = $(".bulk_action input[name='table_records']:checked").length;
    a ? ($(".column-title").hide(), $(".bulk-actions").show(), $(".action-cnt").html(a + " Records Selected")) : ($(".column-title").show(), $(".bulk-actions").hide())
}

function gd(a, b, c) {
    return new Date(a, b - 1, c).getTime()
}

!function (a, b) {
    var c = function (a, b, c) {
        var d;
        return function () {
            function h() {
                c || a.apply(f, g), d = null
            }

            var f = this,
                g = arguments;
            d ? clearTimeout(d) : c && a.apply(f, g), d = setTimeout(h, b || 100)
        }
    };
    jQuery.fn[b] = function (a) {
        return a ? this.bind("resize", c(a)) : this.trigger(b)
    }
}(jQuery, "smartresize");

var CURRENT_URL = window.location.href.split("#")[0].split("?")[0],
    randNum = function () {
        return Math.floor(21 * Math.random()) + 20
    };
$(document).ready(function () {
    $(".collapse-link").on("click", function () {
        var a = $(this).closest(".x_panel"),
            b = $(this).find("i"),
            c = a.find(".x_content");
        a.attr("style") ? c.slideToggle(200, function () {
            a.removeAttr("style")
        }) : (c.slideToggle(200), a.css("height", "auto")), b.toggleClass("fa-chevron-up fa-chevron-down")
    })

    $(".close-link").click(function () {
        var a = $(this).closest(".x_panel");
        a.remove()
    });
})

$(document).ready(function () {
    $('[data-toggle="tooltip"]').tooltip({
        container: "body"
    })
})

$(".progress .progress-bar")[0] && $(".progress .progress-bar").progressbar(), $(document).ready(function () {
    if ($(".js-switch")[0]) {
        var a = Array.prototype.slice.call(document.querySelectorAll(".js-switch"));
        a.forEach(function (a) {
            new Switchery(a, {
                color: "#26B99A"
            })
        })
    }
})

$(document).ready(function () {
    $("input[type=checkbox], input[type=radio]").iCheck({
        checkboxClass: 'icheckbox_square-green',
        radioClass: 'iradio_square-green',
        increaseArea: '20%' // optional
    });
})

$("table input").on("ifChecked", function () {
    checkState = "", $(this).parent().parent().parent().addClass("selected"), countChecked()
})

$("table input").on("ifUnchecked", function () {
    checkState = "", $(this).parent().parent().parent().removeClass("selected"), countChecked()
});


var checkState = "";
$(".bulk_action input").on("ifChecked", function () {
    checkState = "", $(this).parent().parent().parent().addClass("selected"), countChecked()
})

$(".bulk_action input").on("ifUnchecked", function () {
    checkState = "", $(this).parent().parent().parent().removeClass("selected"), countChecked()
})

$(".bulk_action input#check-all").on("ifChecked", function () {
    checkState = "all", countChecked()
})

$(".bulk_action input#check-all").on("ifUnchecked", function () {
    checkState = "none", countChecked()
})

$(document).ready(function () {
    $(".expand").on("click", function () {
        $(this).next().slideToggle(200), $expand = $(this).find(">:first-child"), "+" == $expand.text() ? $expand.text("-") : $expand.text("+")
    })
})

"undefined" != typeof NProgress && ($(document).ready(function () {
    NProgress.start()
}), $(window).load(function () {
    NProgress.done()
}));


var originalLeave = $.fn.popover.Constructor.prototype.leave;
$.fn.popover.Constructor.prototype.leave = function (a) {
    var c, d,
        b = a instanceof this.constructor ? a : $(a.currentTarget)[this.type](this.getDelegateOptions()).data("bs." + this.type);
    originalLeave.call(this, a), a.currentTarget && (c = $(a.currentTarget).siblings(".popover"), d = b.timeout, c.one("mouseenter", function () {
        clearTimeout(d), c.one("mouseleave", function () {
            $.fn.popover.Constructor.prototype.leave.call(b, b)
        })
    }))
}, $("body").popover({
    selector: "[data-popover]",
    trigger: "click hover",
    delay: {
        show: 50,
        hide: 400
    }
}), $(document).ready(function () {
    // 图片预览
    // $(".showImage").fancybox();
    ssr.initDaterangepicker();
    ssr.initValidator();
    ssr.initSidebar();
    $("select.zydSelect").zydSelect();
});

function loadMainCenterDiv(url) {
    if (url == '' || url == '#' || url == '/' || url == '无') {
        return false;
    }
    if (url.indexOf("http") == -1) {
        // url = '${ctx}'+url;
        loadDiv('contentId', url);
    } else {
        if (url.indexOf("?") > -1) {
            url = url + ''
        } else {
            url = url + '?'
        }
        var newiframe = $("<iframe id='mainCenterDiviframe'   width='100%' height='93%'  src='" + url + "'></iframe>");
        $("#contentId").html(newiframe);

    }
}

/**
 *  中心部分div加载
 * @param divId
 * @param url
 * @param type
 */
function loadDiv(divId, url, type) {
    //移除绑定事件
    $(document).unbind('keydown');
    url = timestamp(url);
    if (type == undefined) {
        url = url + "&loadDivId=" + divId;
    } else {
        url = url + "&loadDivId=" + type;
    }
    $("#" + divId).load(url, '', function () {

    })
}


//解决浏览器缓存
function timestamp(url) {
    var getTimestamp = new Date().getTime();
    if (url.indexOf("?") > -1) {
        url = url + "&timestamp=" + getTimestamp
    } else {
        url = url + "?timestamp=" + getTimestamp
    }
    return url;
}